package test.web.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import test.util.RemoteCallUtil;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author piaoransheng
 * @Date 2021/10/27 11:18
 */
@RestController
@RequestMapping("/wx")
public class WXController {

    //服务接入微信
    @GetMapping("/receiveFromWX")
    public void receiveFromWX(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("本地后端服务接入微信公众号平台提交");
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.println(request.getParameter("echostr"));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取用户发来的信息
    @PostMapping("/receiveFromWX")
    public void receiveFromWX(HttpServletRequest request) throws IOException {
        System.out.println("微信发来消息");
        ServletInputStream inputStream = request.getInputStream();
        byte[] byteArray = new byte[1024];
        int len;
        StringBuilder stringBuilder = new StringBuilder();
        while ((len = inputStream.read(byteArray)) != -1) {
            stringBuilder.append(new String(byteArray, 0, len));
        }
        System.out.println(stringBuilder.toString());
    }

    //获取token
    @GetMapping("/getAccessToken")
    public String getAccessToken() {
        String appId = "wxaadab9d8a13fd425";
        String secret = "4c7efbbb7bc3ae8bc32d9b22965cab9d";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        url = url.replace("APPID", appId).replace("APPSECRET", secret);
        return RemoteCallUtil.get(url);
    }
}